$ = layui.$;
var table = '';
var form = '';
var editStudentData = '';//待编辑行的学生信息
var pathArray = window.location.pathname.split('/');
var secondLevelLocation = pathArray[1];
var loginUrl = window.location.protocol + "//"  + window.location.host + "/"+ secondLevelLocation;

layui.use(['table','form'],function(){
    table = layui.table;
    form = layui.form;
    layer.msg("欢迎来到朋友列表");
    //第一个实例
    table.render({
        elem: '#studentTable'
        ,height: 312
        ,url: loginUrl+'/getStudentList.do' //数据接口
        ,page: true //开启分页
        , limits: [3, 5, 10]  //一页选择显示3,5或10条数据
        , limit: 10  //一页显示10条数据
        , parseData: function (res) { //将原始数据解析成 table 组件所规定的数据，res为从url中get到的数据
            var result;
            // console.log(this);
            // console.log(JSON.stringify(res));
            if (this.page.curr) {
                result = res.data.slice(this.limit * (this.page.curr - 1), this.limit * this.page.curr);
            }
            else {
                result = res.data.slice(0, this.limit);
            }
            return {
                "code": res.code, //解析接口状态
                "msg": res.msg, //解析提示文本
                "count": res.count, //解析数据长度
                "data": result //解析数据列表
            };
        }


        ,toolbar: 'default' //开启工具栏，此处显示默认图标，可以自定义模板，详见文档
        ,cols: [[ //表头
            {type: 'checkbox', fixed: 'left'},
            {field: 'id', title: 'ID', width:80, sort: true, fixed: 'left'}
            ,{field: 'name', title: '用户名',}
            ,{field: 'age', title: '年龄', }
            ,{field: 'sex', title: '性别', templet:function (d) {
                    if(!d.sex){
                        return"男"
                    }
                    else {return "女"}
                }
            }
            ,{field: 'hometown', title: '家乡'}
            ,{field: 'hobby', title: '爱好'},
        ]]
    });
    //监听头工具栏事件
    table.on('toolbar(userFi)', function(obj){
        var checkStatus = table.checkStatus(obj.config.id);
        editStudentData = checkStatus.data; //获取选中的数据
        switch(obj.event){
            case 'add':
                addStudentOpen()
                layer.msg('添加');
                break;
            case 'update':
                if(editStudentData.length === 0){
                    layer.msg('请选择一行');
                } else if(editStudentData.length > 1){
                    layer.msg('只能同时编辑一个');
                } else {
                    //layer.alert('编辑 [id]：'+ editStudentData[0].id);
                    updStudentOpen(editStudentData[0].id);
                }
                break;
            case 'delete':
                if(editStudentData.length === 0){
                    layer.msg('请选择一行');
                } else {
                    delById(editStudentData[0].id)
                    location.reload();
                    layer.msg('删除');
                }
                break;
        }
    });
    //监听提交
    form.on('submit(demo1)', function(data){
        layer.alert(JSON.stringify(data.field), {
            title: '最终的提交信息'
        })
        searchStudent(data)
        return false;
    });
    //完全重载表格
    function reloadAll(a) {
        a.reload('studentTable', {
            url: loginUrl+'/getStudentList.do',
            page: {
                curr: 1
            }
        })
    }
//查询
    function searchStudent(comedata) {
        var data = comedata.field
        var name = data.name;
        var age = data.age;
        var sex =data.sex;
        var hometown = data.hometown;
        var hobby = data.hobby;
        if (name == null) {
            reloadAll(table);
        } else {
            table.reload('studentTable', {
                url: loginUrl+'/getStudentList.do',
                where: {
                    name: name,
                    age:age,
                    sex:sex,
                    hometown:hometown,
                    hobby:hobby,
                },
                page: {
                    curr: 1
                }
            })
        }
    }
//新增
    function addStudentOpen() {
        layer.open({
            type: 1,
            title: "新增",
            area: ['50%', '50%'],
            btn: ['确定', '取消'],
            content: $("#addStudentFormDiv"),
            yes: function (index, layero) {
                $.post(loginUrl+"/addStudent.do", {
                    name: $('#name').val(),
                    //单选框取值
                    sex:  $('#sex input[name="sex"]:checked ').val(),
                    age: $('#age').val(),
                    hometown: $('#hometown').val(),
                    hobby: $('#hobby').val()
                }, function (data) {
                    //根据后台返回的参数，来进行判断
                    console.log(data);
                    if (data) {
                        layer.alert('增加成功', {icon: 1, title: '提示'}, function (i) {
                            layer.close(i);
                            layer.close(index);//关闭弹出层1
                        })
                        table.reload('studentTable', {//重载表格
                            page: {
                                curr: 1
                            }
                        })
                    }
                });
            },
            end :function () {
                //重载表单
                $('#addStudentForm').trigger("reset")
                //form.render(null, 'addStudentForm');
            }
        });

    }
//修改
    function updStudentOpen(StudentId) {
    //给表单赋值
    form.val("addStudentForm", { //formTest 即 class="layui-form" 所在元素属性 lay-filter="" 对应的值
        "name": editStudentData[0].name // "name": "value"
        ,"sex": editStudentData[0].sex
        ,"age": editStudentData[0].age
        ,"hometown": editStudentData[0].hometown
        ,"hobby": editStudentData[0].hobby
    });
    layer.open({
        type: 1,
        title: "修改",
        area: ['50%', '50%'],
        btn: ['确定', '取消'],
        content: $("#addStudentFormDiv"),
        yes: function (index, layero) {
            $.post(loginUrl+"/updStudent.do", {
                id:StudentId,
                name: $('#name').val(),
                //单选框取值
                sex:  $('#sex input[name="sex"]:checked ').val(),
                age: $('#age').val(),
                hometown: $('#hometown').val(),
                hobby: $('#hobby').val()
            }, function (data) {
                //根据后台返回的参数，来进行判断
                if (data) {
                    console.log(data)
                    layer.alert('编辑成功', {icon: 1, title: '提示'}, function (i) {
                        layer.close(i);
                        layer.close(index);//关闭弹出层1
                    })
                    table.reload('studentTable', {//重载表格
                        page: {
                            curr: 1
                        }
                    })
                }
            });
        },
        end :function () {
            //重载表单
            $('#addStudentForm').trigger("reset")
            //form.render(null, 'addStudentForm');
        }
    });

}
//删除
    function delById(studentId) {
        $.ajax({
            url:loginUrl+ "/delStudentById.do" ,
            type:'post',
            data:{
                id: studentId
            },
            dataType: 'json',
            success:function(data){
                if(data){
                    layer.close(index);//关闭弹出层
                    //renderTable();  //刷新表格
                }
                else{
                    layer.alert(data);
                    layer.alert("删除失败");
                    // renderTable();
                }
            }
        });
    }
});

